var funcCB_List;
var menuWindow;
var oWS = {};
var MenuID;
var _ID_ = "ApplicantID";
function userGroups(){
	if( typeof(userGroupsList) != 'undefined' )return new UserGroups(userGroupsList);
	return  new UserGroups('');
}

function copyList(){
	var tbl = _listTable();
	if( !tbl )return alert("No list to save.");
	var bColor = tbl.borderColor;
	tbl.borderColor = "Gray";
	debugger;
	frmSave.text.value = tbl.outerHTML.replace(/<input[^>]+>/ig,"").replace(/style="[^"]+"/i,"");
	tbl.borderColor = bColor;
	frmSave.contentType.value = "application/x-msexcel";
	frmSave.fileName.value = _menuPath().split(">")[1]+".xls";
	frmSave.submit();
	return;
}
function listLoadNext(applID){
	clearTimeout(listLoadNext.proc);
	listLoadNext.proc = setTimeout(function(){return getNextFromList()},500);
}
function refreshOnSendToMenu(eo){
	startListRefresh();
	return;
	/////////////////////////////////////////////////
	var applID = eo.applID;
	var pos = applID ? findRowByFieldValue(_listRS(),_ID_,applID) : 0;
	if( !applID || pos >= 0 ){
		clearTimeout(refreshOnSendToMenu.proc);
		refreshOnSendToMenu.proc = setTimeout("listRefresh()",500);
	}
}
function changeFilter(filters){
	for( var filter in filters )
		for( var i = 0; i < search.length; i++ )
			if( search[i].field.match(new RegExp("^"+filter+"$","i")) ){
				search[i].value = filters[filter];
				filterDSO(search[i]);
			}
}
function onListRefresh(eo){
	if( eo.menuPath && !MenuPath.match(new RegExp(eo.menuPath,"i")) )return;
	startListRefresh();
}
function startListRefresh(){
	clearTimeout(startListRefresh.proc);
	startListRefresh.proc = setTimeout(function(){listRefresh()},1000);
}
function page_Load(){
	attachToMouseDown();
	attachToSendToMenu(refreshOnSendToMenu);
	attachToListLoadNext(listLoadNext);
	attachToFilterChange(changeFilter);
	attachToListRefresh(onListRefresh);
}
function tree_Load(oTree){
	if( arguments.length == 1 )return setTimeout(function(){return tree_Load(oTree,true);},1000);
	oTree.treeNodeSrc = "Lists.asmx/MenuTreeXML";
	oTree.databind();
}
function showApplInfo(ev){
	if( ev.fieldName )return doOnSelect(ev.fieldName);
	if( typeof(ev.cancelBubble) == "boolean" )ev = ev.srcElement;
	var applID = typeof ev == 'string' ? ev : ev.rs ? ev.rs(_ID_).Value : rsField(ev,_ID_).Value;
	if( !applID )return alert("No "+_ID_+" was provided.");
	var menuParam = applID ? "" : "&menuID="+MenuID;
	var url = "/Manager/Menu/ShowApplicant.aspx?ApplID="+applID;
	var w =	top.open(url+menuParam,"APPLICATION_"+applID,features("status=yes"));
	var count = 10;
	_setWindowFocus.proc = setInterval(function(){_setWindowFocus()},1000);
	//Local
	function _setWindowFocus(){
		try{w.focus();count=0;
		}catch(e){return;}
		if( !count ){
			//status = "Got Focus! "+_setWindowFocus.proc;
			return clearInterval(_setWindowFocus.proc);
		}
	}
}
var wins = new Array();
function closeWins(){
	for( var w=0; w < wins.length; w++ )
		try{wins[w].close()}catch(e){}
}
function showSubMenuItem(menuID,params,action,attributes,heading,menuPath,onArrive,onRowClick){
var pn,cm,to,un,pw,hd,ep;
	//status = 'menuID['+menuID+'],'+'params:['+params+'],'+'action:['+action+'],'+'attributes:['+attributes+'],'+'heading:['+heading+'],'+'menuPath:['+menuPath+"]";
	switch( params.toLowerCase() ){
		case '':
		case 'list':
			//if( typeof(ws.createCallOptions) == 'undefined' )return alert("Page is still loading ...");
			MenuID = menuID;
			MenuPath = menuPath;
			top.OnRowClick = onRowClick ? eval(onRowClick) : doOnSelect;
			_listMenuID(menuID);
			var filters = {};
			eval(onArrive);
			oWS.cb = function(result){onListReady(result,menuID,filters)};
			oWS.co = ws.createCallOptions(action.replace(/[(].+/,""),pn,true,to,un,pw,hd,ep,_getParams(action));
			if( getList() )_menuPath(menuPath).split(">")[1];
			break;
		case 'eval':
			var showParams = ["status=no","resizable=yes","dialogWidth=100px"];
			eval(action);
			break;
		case 'window':
			if( !event.ctrlKey ){
				var url = attributes.toLowerCase() == "eval" ? eval(heading) : action+(heading||"");
				if( url )menuWindow = open(url,"MENU_"+menuID,features("status=yes"));
				wins.push(menuWindow);
				break;
			}
		case 'popup':
			showParams = ["status=no","resizable=yes","dialogWidth=700px","dialogHeight=500px","dialogTop="+event.screenY+"px","dialogLeft="+event.screenX+"px"];
			if( action.indexOf('"') != 0 )action = "'"+action.replace("'","\\'")+"'";
			var url = eval(action);
			if( url )menuWindow = showModelessDialog(url,{opener:top},showParams.join(";"));
			wins.push(menuWindow);
			return menuWindow;
		case 'link':
			try{menuWindow.close()}catch(e){}
			top.location.replace(action);
			break;
		case 'interactive':
			eval(action);
			break;
	}
	//if( getList() )spnMenuPath.innerText = menuPath;
	///Locals
	
	function _getParams(action){//debugger;
		var abc = "abcdefghij";
		var p;
		var a = action.match(/[(](.+)[)]/);
		a = !a ? new Array("menuID") : a[1].split(",");
		for( var i=0,j=0,aa=new Array(); i < a.length; i++ ){
			var s = unescape(a[i]);
			if( !s.match(/^['"]/) )aa[s] = eval(s);
			else aa[abc.charAt(j++)] = s.substr(1,s.length-2);
		}
		return aa;
	}
	// ***** interactives *****
	function listWhere(){
		var url = "/Manager/ShowRS.aspx?servicePath="+escape("/Manager/Menu/Lists.asmx?");
		wins.push(showModelessDialog(url+"&serviceFunc="+escape("ListWhere(null)")+"&onFilter=ListWhere&title=Find Applicant",{opener:self,onSelect:showApplInfo},"resizable:1;status:0;help:0"));
	}
	// +++++ interactives +++++
}
function showRowMenu(){
	var e = event.srcElement;
	var menu = new DropMenu("mnuFly");
	if( !menu.menuID )return false;
	menu.imageStyle += ";margin-top:0px;margin-bottom:0px";
	menu.add("Copy","copyElement(ce)");
	menu.add("Send To ...","showNexus(ce)");
	menu.add("Menu History","showMenuHistory(ce)");
	menu.add("Show Last Fax","showFaxHistory(ce)");
	if( typeof(showRowMenu_NS) != "undefined" )showRowMenu_NS(menu);
	menu.menuShow(getLeftPos(e),event.y-event.offsetY+e.offsetHeight-3);
	event.cancelBubble = true;
	return false;
}
function showFaxHistory(ce){
	var applID = rsField(ce,_ID_).value;
	var showParams = ["status=no","resizable=yes"].join(";");
	showModelessDialog("/manager/Common/FaxHistory.aspx?ApplID="+applID,null,showParams);
}
var MENU_HISTORY_URL = "/manager/administrator/MenuHistory.aspx?ApplID=";
function showMenuHistory(ce){
	var applID = rsField(ce,_ID_).value;
	var showParams = ["status=no","resizable=yes","dialogWidth=100px","dialogHeight=100px"].join(";");
	showModelessDialog(MENU_HISTORY_URL+applID,null,showParams);
}
function showNexus(ce){
	var applID = rsField(ce,_ID_).value;
	var showParams = ["status=no","resizable=yes","dialogWidth=100px","dialogHeight=100px"].join(";");
	_reload("/manager/admin/nexus.aspx?ApplID="+applID);
	//Local
	function _reload(url){
		showModelessDialog(url,{opener:self,reload:_reload},showParams);
	}
}
function logOf(){
	closeWins();
	top.document.execCommand("ClearAuthenticationCache");
	top.location.reload();
}
function getList(){
	if( WS ){
		WS(oWS.cb,oWS.co);
		return true;
	}
	setTimeout("getList()",100);
}
function onListReady(result,menuID,filters){
	var bid = onListReady.bid;
	if( showSOAPError(result) )return;
	var tbl = _listTable();
	//if( tbl )tbl.removeBehavior(bid);
  if( contents.children[0] && !onListReady.tree){
		contents.removeChild(contents.children[0]).outerHTML = "";
		onListReady.tree = true;
	}
	if( !tbl )tbl = refreshListTable();
	tbl.menuID = menuID;
	dso.recordset.Filter = 0;
	dso.recordset.Sort = "";
	if( loadDSO(dso,result.value) ){
		tbl = refreshListTable();
		showDSO(dso,tbl);
	}
	for( var filter in filters )
		for( var i = 0; i < search.length; i++ )
			if( search[i].field.match(new RegExp("^"+filter+"$","i")) ){
				search[i].value = filters[filter];
				filterDSO(search[i]);
			}
}
function refreshListTable(){
	if( contents.children[0] )contents.removeChild(contents.children[0]).outerHTML = "";
	var tbl = contents.appendChild(divListTempl.cloneNode(true));
	tbl.style.display="";
	return _listTable();
}
function getNextFromList(pos){
	if( !_listTable() )return alert("Pull the list to take a next applicant from.");
	listRefresh(pos);// refresh list and click on row at selected position
	_listTable().onrowclick = _loadNext;
	// Locals
	function _loadNext(){//loads first avalible applicant starting with current
		_listTable().onrowclick = null;
		var row = event.srcRow;
		var ret = WS(CO("LockNextApplicant"),fieldByName(row,_ID_),_listMenuID());
		if( showSOAPError(ret) )return;
		if( ret.value ){
			_startPos(-1);
			return row.cells[0].click();
		}
		var pos = _listPos(row);
		if( _startPos() < 0 )_startPos(pos);
		else if( _startPos() == pos )return _startPos(-1);
		if( ++pos >= _listRecordCount() )return getNextFromList(0);
		_listTable().onrowclick = _loadNext;
		_listRow(pos).click();
		// Local
		function _startPos(pos){
			pos = pos + '';
			return parseInt(arguments.length  ? (getNextFromList.startPos = pos) : (getNextFromList.startPos||-1));
		}
	}
}
function listRefresh(pos){
	if( !_listTable() )return;
	if( !defined(pos) )pos = _listSelRow() ? _listSelPos() : 0;
	var filter = _listFilter();
	var sort = _listSort();
	var table = _listTable();
	oWS.cb = function(ret){__cb(ret,pos,filter,sort)};
	getList();
	///oWS.co.async = false;
	///var ret = WS(oWS.co);
	///if( showSOAPError(ret) )return;
	///__cb(ret,pos,filter,sort);
	// Locals
	function __cb(ret,pos,filter,sort){// call back for list refresh after getList()
		if( showSOAPError(ret) )return;
		dso.recordset.Filter = 0;
		dso.recordset.Sort = "";
		var newRS = loadDSO(dso,ret.value);
		_listFilter(filter);
		_listSort(sort);
		if( _listRecordCount() == 0 )return;
		if( pos >= _listRecordCount() )pos = 0;
		if( pos >= 0 )
			if( newRS )table.onready = __click;
			else __click();
		//table.attachEvent("onreadystatechange",__click);
		// Locals
		function __click(){//click on row after rs was populated in table list
			if(table.readyState!="complete")return;
			//status = "_click.pos:"+pos;
			setTimeout(function(){try{_listTable().DoClick(pos);}catch(e){}},100);
			table.onready = null;
			//table.detachEvent("onreadystatechange",arguments.callee);
		}
		function __findRowByFieldValue(field,value){
			var rs = _listRS();
			rs.MoveFirst();
			rs.Find(field+" = "+value);
			return rs.EOF ? -1 : rs.AbsolutePosition - 1;
		}
	}
}
function attachBehavior(tbl,thread){
	if( tbl.readyState != "complete" )return;
//	if( tbl.behaviorUrns.length || tbl.behaviorUrns[tbl.behaviorUrns.length-1] != "" )return;
	if( !thread ){
		clearTimeout(attachBehavior.proc);
		attachBehavior.proc = setTimeout(function(){attachBehavior(tbl,true)},1000);
		return;
	}
	tbl.addBehavior("/include/HTC/rowover_js.htc");
	try{
		var rs = getDataSrcRS(tbl);
		var zs = getZs(rs);
		status = rs.recordCount+" item"+(rs.recordCount==1?"":"s")+"."+zs.join("; ");
	}catch(e){}
}
function getZs(rs){
	var Zs = new Array;
	if( !rs.recordCount )return fieldNames;
	for( var f=0; f < rs.Fields.Count; f++ ){
		var func = (rs.Fields(f).Name.match(/^(.{3})__/)||{})[1];
		if( !func )continue;
		switch( func ){
			case 'Sum': var aggr = __Sum(rs,rs.Fields(f).Name);break;
			case 'Avg': var aggr = __Avg(rs,rs.Fields(f).Name);break;
		}
		Zs.push(__formatAggr(rs.Fields(f).Name,aggr));
	}
	return Zs;
	//Local
	function __formatAggr(fieldName,aggr){
		var name = {func:fieldName.substr(0,1),name:fieldName.match(/[^_]+$/)};
		return name.name+"("+name.func+"):"+__formatNumber(aggr);
	}
	function __Sum(rs,fieldName){
		var sum = 0;
		for( rs.MoveFirst(); !rs.EOF; rs.MoveNext() )
			sum += rs.Fields(fieldName).value;
		return sum;
	}
	function __Avg(rs,fieldName){
		return Math.round(100*__Sum(rs,fieldName)/rs.recordCount)/100;
	}
	function __formatNumber(n){
		n = new Number(n);
		var s  = n.toLocaleString();
		return n >= 100 ? s.replace(/[.]\d\d$/,"") : s;
	}
}
function features(add){
var s = ",status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes,top=0,left=0,"+(add||'');
var statusBar = s.match(/status=yes/i)?true:false;
	return "height="+(screen.availHeight-30-(statusBar?30:0))+",width="+(screen.availWidth-10)+s;
}
// ***** Properties
function _listFilter(v){
	var rs = _listRS();
	if( defined(v) )rs.Filter = v;
	return rs.Filter;
}
function _listSort(v){
	var rs = _listRS();
	if( defined(v) )rs.Sort = v;
	return rs.Sort;
}
function _listPos(row){return ((row||{}).rowIndex||0)-1}
function _listRS(){return getDataSrcRS(dso)}
function _listRecordCount(){return _listRS().recordCount}
function _listTable(){return contents.all.tblTempl}
function _listBodies(){return _listTable().tBodies}
function _listRow(pos){return _listBodies()[pos].rows[0]}
function _listSelRow(){return (_listTable()||{}).selRow}
function _listSelPos(){return _listPos(_listSelRow())}
function _listMenuID(v){
	if( defined(v) )_listMenuID.menuID = v;
	return _listMenuID.menuID;
}
function _filters(){return _listTable().tHead.all.tags("INPUT")}
function _menuPath(v){
	if( arguments.length )spnMenuPath.innerHTML = v;
	return spnMenuPath.innerText;
}
//var d=new Date(new Date()-1000*60*60*24*30);filters["Date In"] = d.getFullYear()+"/"+formatXXX(d.getMonth()+1,"00")+"/"+formatXXX(d.getDate(),"00")+"~"
function dateRangeFilter(daysBack,daysForward){
	return formatDate(dateAdd("dd",-daysBack))+"~"+formatDate(dateAdd("dd",daysForward));
}